package longfly.development;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;

public class Check_Sell extends Activity {
    /** Called when the activity is first created. */
	SQLiteDatabase db;
    private ArrayList<HashMap<String,String>> list=null;
    private HashMap<String,String>map=null;
	SimpleAdapter adapter;

	/********以下是对话框内的控件**************************/
	Button		DIALOG_BTN_OK;
	Button		DIALOG_BTN_CANCEL;
	TextView	DIALOG_TX_TIME;
	DatePicker  DIALOG_DATEPICKER;
	TimePicker  DIALOG_TIMEPICKER;
	/****************************************************/
	Button	BTN_EXIT;
	Button	BTN_CHAXUN;
	Button	BTN_START_DATE;
	Button	BTN_END_DATE;
	Button	BTN_CREATE,	BTN_INSERT;	
	ListView	LS;
   	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.i800_check_sell);
        
       find_id();
       key_things();
 	   db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);	
}

	private void key_things() {
		BTN_CHAXUN.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   	   	String start_time,end_time;
		   	   	start_time = BTN_START_DATE.getText().toString();
		   	   	end_time = BTN_END_DATE.getText().toString();
		   		String[] refer = {start_time , end_time};
				Cursor  cursor = db.rawQuery("select * from lfcy_base_sample where timestamp > ? and timestamp < ? order by cSellNo",refer);
				fill_hashmap(cursor);
				inflateList(cursor);				}
	    });	
		BTN_EXIT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		db.close();
		   		finish();
		   	}
	    });	
		BTN_START_DATE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		START_END = true;
                showDialog(DIALOG_FIND);
		   	}
	    });			
		BTN_END_DATE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		START_END = false;
                showDialog(DIALOG_FIND);
		   	}
	    });	
		BTN_CREATE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		sql_control sqlc = new sql_control();
		   		sqlc.create_table_sample(db, "ok");
/*		   		sqlc.insert_table_sample(db,"2013-01-01" ,"1");
		   		sqlc.insert_table_sample(db,"2013-01-02" ,"2");
		   		sqlc.insert_table_sample(db,"2013-02-01" ,"3");
		   		sqlc.insert_table_sample(db,"2013-02-02" ,"4");
		   		sqlc.insert_table_sample(db,"2013-03-01" ,"5");
		   		sqlc.insert_table_sample(db,"2013-04-01" ,"6");
		   		sqlc.insert_table_sample(db,"2013-05-01" ,"7");
		   		sqlc.insert_table_sample(db,"2013-05-02" ,"8");
		   		sqlc.insert_table_sample(db,"2013-05-03" ,"9");
		   		sqlc.insert_table_sample(db,"2013-06-01" ,"11");
		   		sqlc.insert_table_sample(db,"2013-06-02" ,"12");
		   		sqlc.insert_table_sample(db,"2013-07-01" ,"13");
		   		sqlc.insert_table_sample(db,"2013-07-02" ,"14");
		   		sqlc.insert_table_sample(db,"2013-07-03" ,"15");
		   		sqlc.insert_table_sample(db,"2013-08-01" ,"1");
		   		sqlc.insert_table_sample(db,"2013-08-02" ,"11");
		   		sqlc.insert_table_sample(db,"2013-09-01" ,"11");
		   		sqlc.insert_table_sample(db,"2013-09-02" ,"111");
		   		sqlc.insert_table_sample(db,"2013-10-01" ,"111");
		   		*/
		   	}
	    });	
		BTN_INSERT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		sql_control sqlc = new sql_control();
			    Random ran = new Random();
			    int rand = ran.nextInt(200);
		   		sqlc.insert_table_sample(db, ""+rand);
		   		refch_list(); 
		   	}
	    });	
		
		LS.setOnItemClickListener(new OnItemClickListener() {
			@Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
			{
				// TODO Auto-generated method stub
				HashMap<String,String> map = (HashMap<String,String>)parent.getItemAtPosition(position);
                String CaiCode 	=	String.valueOf(map.get("_id"));
				
		   		sql_control sqlc = new sql_control();
		   		sqlc.remove_table_sample(db, CaiCode);
		   		refch_list(); 	
			}
		});	
	}

	protected void refch_list() {
   		//cursor里面存了所有从数据库里读出的数据！这时还仅仅是数据！跟显示没有半毛钱关系！
		Cursor  cursor = db.rawQuery("select * from lfcy_base_sample order by cSellNo DESC", null);
		fill_hashmap(cursor);
		inflateList(cursor);			
	}

	//创建并新建一个Hashmap
	private ArrayList fill_hashmap(Cursor cursor) {
	    list=new ArrayList<HashMap<String,String>>();
		int i=0;
		while(cursor.moveToNext()) {
			i++;
            map=new HashMap<String,String>();           
            map.put("_id", cursor.getString(cursor.getColumnIndex("_id")));
            map.put("cSellNo", cursor.getString(cursor.getColumnIndex("cSellNo")));
            String myDate = cursor.getString(cursor.getColumnIndex("timestamp"));  
			map.put("timestamp", myDate);

            list.add(map);
		}
		
		return list;
	}
	
	private void inflateList(Cursor cursor)
	{
		//将数据与adapter集合起来
        adapter = new SimpleAdapter(
        		this, 
				list, 
				R.layout.imx_liushui_check 
				, new String[]{	"_id" 	,"timestamp", "cSellNo" }
				, new int[]{R.id.liushui_check_1 , R.id.liushui_check_7,R.id.liushui_check_3 }
        );
		
		//显示数据
		LS.setAdapter(adapter);
	}
	
	private void find_id() {
		BTN_EXIT		=	(Button) findViewById(R.id.liuchui_check_exit);
		BTN_CHAXUN		=	(Button) findViewById(R.id.liuchui_check_chaxun);
		BTN_START_DATE	=	(Button) findViewById(R.id.liuchui_check_start);
		BTN_END_DATE	=	(Button) findViewById(R.id.liuchui_check_end);
		LS				=	(ListView) findViewById(R.id.liushui_check_list);		
		BTN_CREATE		=	(Button) findViewById(R.id.check_sell_create);
		BTN_INSERT		=	(Button) findViewById(R.id.check_sell_insert);
	}

	/***      初始化时间对话框！ 命名为buildDialog      ***/
   	int	now_year,now_month,now_day,now_hour,now_minute;
	int sYear,sMounth,sDay,sHour,sMinute;	//起始时间记录，和起始按钮的时间要一致
	int eYear,eMounth,eDay,eHour,eMinute;	//结束时间记录，和结束按钮的时间要一致
	boolean	Init_Dialog_S = true;
	boolean	Init_Dialog_E = true;
	boolean	START_END;
   	private int DIALOG_FIND=101;
	private Dialog buildDialog(Context context) {  	
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(R.drawable.other_1); 
        if (START_END) {
            builder.setTitle("选择起始时间");  
		} else {
	        builder.setTitle("选择结束时间");  
		}
        LayoutInflater inflater = LayoutInflater.from(Check_Sell.this);
        View view = inflater.inflate(R.layout.i800dialog_datetime_choose, null);			
        
		if (START_END) {
			if (Init_Dialog_S) {
	            Calendar calc = Calendar.getInstance();
	            now_year  = calc.get(Calendar.YEAR);
	            now_month = calc.get(Calendar.MONTH);
	            now_day   = calc.get(Calendar.DAY_OF_MONTH);
	            now_hour  = calc.get(Calendar.HOUR_OF_DAY);
	            now_minute= calc.get(Calendar.MINUTE);						
			} else {
	            now_year  = sYear;
	            now_month = sMounth;
	            now_day   = sDay;
	            now_hour  = sHour;
	            now_minute= sMinute;
			}
		} else {
			if (Init_Dialog_E) {
	            Calendar calc = Calendar.getInstance();
	            now_year  = calc.get(Calendar.YEAR);
	            now_month = calc.get(Calendar.MONTH);
	            now_day   = calc.get(Calendar.DAY_OF_MONTH);
	            now_hour  = calc.get(Calendar.HOUR_OF_DAY);
	            now_minute= calc.get(Calendar.MINUTE);						
			} else {
	            now_year  = eYear;
	            now_month = eMounth;
	            now_day   = eDay;
	            now_hour  = eHour;
	            now_minute= eMinute;
			}
		}

        builder.setView(view);
        builder.setCancelable(false);
        
		DIALOG_BTN_OK 		= (Button) view.findViewById(R.id.dialog_time_ok);
		DIALOG_BTN_CANCEL 	= (Button) view.findViewById(R.id.dialog_time_cancel);	
		DIALOG_TX_TIME		= (TextView) view.findViewById(R.id.dialog_time_tx);
		DIALOG_TIMEPICKER	= (TimePicker) view.findViewById(R.id.dialog_time_pick);
		DIALOG_DATEPICKER	= (DatePicker) view.findViewById(R.id.dialog_date_pick);
		
		//默认时间格式为12小时制的，这里我们改成24小时的制
		DIALOG_TIMEPICKER.setIs24HourView(true);
		DIALOG_TIMEPICKER.setCurrentHour(now_hour);
		DIALOG_TIMEPICKER.setCurrentMinute(now_minute);	
		
		DIALOG_DATEPICKER.init(now_year, now_month, now_day, new OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// TODO Auto-generated method stub
				now_year  = year;
				now_month = monthOfYear;
				now_day   = dayOfMonth;		
			}
		});
		
		DIALOG_TIMEPICKER.setOnTimeChangedListener(new OnTimeChangedListener() {		
			@Override
			public void onTimeChanged(TimePicker view, int hour, int minute) {
				// TODO Auto-generated method stub
				now_hour = hour;
				now_minute = minute;
			}
		});
			
		DIALOG_BTN_OK.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
				if (START_END) {
		              sYear		=	now_year;
		              sMounth	=	now_month;
		              sDay		=	now_day;
		              sHour		=	now_hour;
		              sMinute	=	now_minute;
		              showData(sYear,sMounth+1,sDay,sHour,sMinute);
				} else {
		              eYear		=	now_year;
		              eMounth	=	now_month;
		              eDay		=	now_day;
		              eHour		=	now_hour;
		              eMinute	=	now_minute;
		              showData(eYear,eMounth+1,eDay,eHour,eMinute);
				}
				if (START_END) {
					Init_Dialog_S = false;					
				} else {
					Init_Dialog_E = false;
				}
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}
	    });
		
		DIALOG_BTN_CANCEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}
	    });
		
        return builder.create();  
    } 
    
	protected void showData(int year2, int month2, int day2, int hour2,
			int minute2) {
		// TODO Auto-generated method stub
		String mMounth,mDay,mHour,mMinute;
		
		if (month2<10) {
			mMounth = "0"+month2;
		}else {
			mMounth = ""+month2;
		}
		
		if (day2<10) {
			mDay = "0"+day2;
		}else {
			mDay = ""+day2;
		}
		if (hour2<10) {
			mHour = "0"+hour2;
		}else {
			mHour = ""+hour2;
		}	
		if (minute2<10) {
			mMinute = "0"+minute2;
		}else {
			mMinute = ""+minute2;
		}		
		DIALOG_TX_TIME.setText("您设置的时间是:         "+year2+"年"+ mMounth+"月"+
				mDay+"日"+mHour+"点"+mMinute+"分");
		
   		if (START_END) {
   			BTN_START_DATE.setText( year2+"-"+mMounth+"-"+mDay +" "+mHour+":"+mMinute );
		} else {
			BTN_END_DATE.setText( year2+"-"+mMounth+"-"+mDay +" "+mHour+":"+mMinute );
		}
	}

	@Override 
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==101){  
        	return this.buildDialog(Check_Sell.this);  
        }
        else{  
            return null;  
        }  
    } 

    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(DIALOG_FIND, dialog);  
    } 
    /***      以上是初始一个对话框！       ***/	 
}